<script setup>
import {ref, onMounted, computed} from 'vue';
import {ElMessage} from 'element-plus';
import dialogBooks from "@/components/dialog/addBookDialog.vue"

//弹出的显示与隐藏
const dialogFormVisible = ref(false);
const books = ref([]);

const currentPage = ref(1);
const pageSize = ref(10);

const getBooksAll = async () => {
  let data = []
  for (let i = 0; i < 1000; i++) {
    data.push({
      id: i,
      bookName: "测试书名" + i,
      author: "测试作者" + i,
      publisher: "测试出版社" + i,
      createdAt: "2024-5-" + i,
      updatedAt: "2024-5-" + i,
    },)
  }
  books.value = data
  //   const response = await axios(config);
  //   if (Array.isArray(response.data.data)) {
  //     books.value = response.data.data.sort((a, b) => a.id - b.id);
  //   } else {
  //     throw new Error("数据格式错误");
  //   }

};

const paginatedBooks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return books.value.slice(start, start + pageSize.value);
});

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

const addBook = async (e) => {
  ElMessage({
    showClose: true,
    message: '添加图书成功',
    type: "success",
  });

};

const deleteRow = async (id) => {
  ElMessage({
    showClose: true,
    message: id + ' 删除成功',
    type: 'success',
  });
};

onMounted(async () => {
  await getBooksAll();
});

</script>

<template>

  <dialogBooks @addBook="addBook" v-model="dialogFormVisible"/>

  <el-table :data="paginatedBooks" style="width: 100%">
    <el-table-column prop="id" label="ID" width="80"/>
    <el-table-column prop="bookName" label="书名" width="120"/>
    <el-table-column prop="author" label="作者" width="120"/>
    <el-table-column prop="publisher" label="出版社" width="120"/>
    <el-table-column prop="createdAt" label="创建时间" width="120"/>
    <el-table-column prop="updatedAt" label="更新时间" width="120"/>
    <el-table-column label="选项操作" min-width="100">
      <template #default="scope">
        <el-button
            link
            type="danger"
            size="small"
            @click.prevent="deleteRow(scope.row.id)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="books.length"
        layout="prev, pager, next"
        style="margin-top: 20px;"
    />
  </div>
  <div class="button-container">
    <el-button type="primary" @click="dialogFormVisible = true">
      新增图书
    </el-button>
  </div>
</template>

<style scoped>
.button-container {
  margin: 20px 0;
  padding-left: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 5px;
}
</style>
